import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public class ExamFrame extends JFrame {
    private Exam exam;
    private User student;
    private List<Question> questions;
    private int currentQuestionIndex = 0;
    private Map<Integer, String> answers = new HashMap<>();
    private ExamRecord examRecord;

    // UI组件
    private JPanel questionPanel;
    private JPanel answerPanel;
    private JPanel answerCardPanel;
    private JLabel questionLabel;
    private JLabel questionInfoLabel;
    private JButton prevButton;
    private JButton nextButton;
    private JButton submitButton;
    private JLabel timeLabel;
    private Timer examTimer;
    private long remainingTime;

    // DAO
    private QuestionDAO questionDAO;
    private AnswerRecordDAO answerDAO;
    private ExamRecordDAO examRecordDAO;

    public ExamFrame(Exam exam, User student) {
        this.exam = exam;
        this.student = student;
        this.questionDAO = new QuestionDAO();
        this.answerDAO = new AnswerRecordDAO();
        this.examRecordDAO = new ExamRecordDAO();

        // 获取考试记录
        this.examRecord = examRecordDAO.getExamRecord(exam.getId(), student.getId());

        // 加载题目
        this.questions = questionDAO.getQuestionsByExamId(exam.getId());

        initComponents();
        setupLayout();
        setupEvents();
        loadQuestion(0);
        startTimer();
    }

    private void initComponents() {
        setTitle("考试进行中 - " + exam.getTitle());
        setSize(1600, 1000);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setResizable(true);

        // 题目面板
        questionPanel = new JPanel(new BorderLayout(10, 10));
        questionPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "题目内容",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));
        questionPanel.setBackground(Color.WHITE);

        questionInfoLabel = new JLabel();
        questionInfoLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        questionInfoLabel.setForeground(new Color(70, 130, 180));

        questionLabel = new JLabel();
        questionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        questionLabel.setVerticalAlignment(JLabel.TOP);
        questionLabel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 答案面板
        answerPanel = new JPanel();
        answerPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(40, 167, 69), 2),
                "答题区域",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(40, 167, 69)));
        answerPanel.setBackground(Color.WHITE);

        // 导航按钮
        Dimension buttonSize = new Dimension(140, 50);
        Font buttonFont = new Font("微软雅黑", Font.BOLD, 16);

        prevButton = new JButton("◀ 上一题");
        prevButton.setPreferredSize(buttonSize);
        prevButton.setFont(buttonFont);
        prevButton.setBackground(new Color(108, 117, 125));
        prevButton.setForeground(Color.WHITE);
        prevButton.setBorder(BorderFactory.createEmptyBorder());
        prevButton.setFocusPainted(false);

        nextButton = new JButton("下一题 ▶");
        nextButton.setPreferredSize(buttonSize);
        nextButton.setFont(buttonFont);
        nextButton.setBackground(new Color(70, 130, 180));
        nextButton.setForeground(Color.WHITE);
        nextButton.setBorder(BorderFactory.createEmptyBorder());
        nextButton.setFocusPainted(false);

        submitButton = new JButton("🎯 提交试卷");
        submitButton.setPreferredSize(new Dimension(160, 50));
        submitButton.setFont(new Font("微软雅黑", Font.BOLD, 18));
        submitButton.setBackground(new Color(220, 53, 69));
        submitButton.setForeground(Color.WHITE);
        submitButton.setBorder(BorderFactory.createEmptyBorder());
        submitButton.setFocusPainted(false);

        // 时间显示
        timeLabel = new JLabel();
        timeLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        timeLabel.setForeground(new Color(220, 53, 69));
        timeLabel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 53, 69), 2),
                BorderFactory.createEmptyBorder(8, 15, 8, 15)));
        timeLabel.setOpaque(true);
        timeLabel.setBackground(new Color(255, 248, 248));

        // 答题卡面板
        answerCardPanel = new JPanel();
        answerCardPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(255, 193, 7), 2),
                "答题卡",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(255, 193, 7)));
        answerCardPanel.setBackground(Color.WHITE);

        // 计算剩余时间
        calculateRemainingTime();
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));

        // 顶部信息面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(70, 130, 180));
        topPanel.setPreferredSize(new Dimension(1600, 90));

        JLabel titleLabel = new JLabel(exam.getTitle(), JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(Color.WHITE);

        JPanel infoPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 20, 15));
        infoPanel.setBackground(new Color(70, 130, 180));

        JLabel studentLabel = new JLabel("👤 考生：" + student.getRealName());
        studentLabel.setForeground(Color.WHITE);
        studentLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));

        JLabel timeIconLabel = new JLabel("⏰ 剩余时间：");
        timeIconLabel.setForeground(Color.WHITE);
        timeIconLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));

        infoPanel.add(studentLabel);
        infoPanel.add(Box.createHorizontalStrut(30));
        infoPanel.add(timeIconLabel);
        infoPanel.add(timeLabel);

        topPanel.add(titleLabel, BorderLayout.CENTER);
        topPanel.add(infoPanel, BorderLayout.EAST);

        // 主要内容面板
        JPanel mainPanel = new JPanel(new BorderLayout(15, 15));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 左侧题目和答案面板
        JPanel leftPanel = new JPanel(new BorderLayout(10, 10));
        leftPanel.setPreferredSize(new Dimension(1150, 800));

        // 题目信息面板
        JPanel questionInfoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 10));
        questionInfoPanel.setBackground(new Color(248, 249, 250));
        questionInfoPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        questionInfoPanel.add(questionInfoLabel);
        questionPanel.add(questionInfoPanel, BorderLayout.NORTH);

        // 题目内容滚动面板
        JScrollPane questionScrollPane = new JScrollPane(questionLabel);
        questionScrollPane.setPreferredSize(new Dimension(1130, 300));
        questionScrollPane.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
        questionScrollPane.getVerticalScrollBar().setUnitIncrement(16);
        questionPanel.add(questionScrollPane, BorderLayout.CENTER);

        // 答案区域滚动面板
        JScrollPane answerScrollPane = new JScrollPane(answerPanel);
        answerScrollPane.setPreferredSize(new Dimension(1130, 400));
        answerScrollPane.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
        answerScrollPane.getVerticalScrollBar().setUnitIncrement(16);

        leftPanel.add(questionPanel, BorderLayout.NORTH);
        leftPanel.add(answerScrollPane, BorderLayout.CENTER);

        // 导航按钮面板
        JPanel navPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 20));
        navPanel.setBorder(BorderFactory.createEmptyBorder(15, 0, 15, 0));
        navPanel.setBackground(new Color(248, 249, 250));

        navPanel.add(prevButton);
        navPanel.add(nextButton);
        navPanel.add(Box.createHorizontalStrut(80));
        navPanel.add(submitButton);

        leftPanel.add(navPanel, BorderLayout.SOUTH);

        // 右侧答题卡面板
        JPanel rightPanel = new JPanel(new BorderLayout(10, 10));
        rightPanel.setPreferredSize(new Dimension(400, 800));

        // 答题卡面板 - 使用包装面板确保按钮不被拉伸
        JPanel cardContainer = new JPanel(new BorderLayout());
        cardContainer.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));

        // 创建一个包装面板，使答题卡居中显示
        JPanel cardWrapper = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
        cardWrapper.add(answerCardPanel);

        cardContainer.add(cardWrapper, BorderLayout.NORTH);

        // 答题卡统计信息
        JPanel statsPanel = createStatsPanel();

        rightPanel.add(cardContainer, BorderLayout.CENTER);
        rightPanel.add(statsPanel, BorderLayout.SOUTH);

        mainPanel.add(leftPanel, BorderLayout.CENTER);
        mainPanel.add(rightPanel, BorderLayout.EAST);

        add(topPanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);

        // 创建答题卡
        createAnswerCard();
    }

    private void setupEvents() {
        prevButton.addActionListener(e -> {
            saveCurrentAnswer();
            if (currentQuestionIndex > 0) {
                loadQuestion(currentQuestionIndex - 1);
            }
        });

        nextButton.addActionListener(e -> {
            saveCurrentAnswer();
            if (currentQuestionIndex < questions.size() - 1) {
                loadQuestion(currentQuestionIndex + 1);
            }
        });

        submitButton.addActionListener(e -> submitExam());

        // 添加按钮悬停效果
        prevButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (prevButton.isEnabled()) {
                    prevButton.setBackground(new Color(90, 98, 104));
                }
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (prevButton.isEnabled()) {
                    prevButton.setBackground(new Color(108, 117, 125));
                }
            }
        });

        nextButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (nextButton.isEnabled()) {
                    nextButton.setBackground(new Color(57, 107, 147));
                }
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (nextButton.isEnabled()) {
                    nextButton.setBackground(new Color(70, 130, 180));
                }
            }
        });

        submitButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                submitButton.setBackground(new Color(200, 35, 51));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                submitButton.setBackground(new Color(220, 53, 69));
            }
        });

        // 防止意外关闭
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                int result = JOptionPane.showConfirmDialog(
                        ExamFrame.this,
                        "确定要退出考试吗？\n退出后将自动提交试卷！",
                        "确认退出",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE);
                if (result == JOptionPane.YES_OPTION) {
                    submitExam();
                }
            }
        });
    }

    private void createAnswerCard() {
        // 使用FlowLayout来避免按钮被拉伸
        answerCardPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
        answerCardPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        for (int i = 0; i < questions.size(); i++) {
            final int index = i;
            JButton cardButton = new JButton(String.valueOf(i + 1));

            // 设置固定的小正方形尺寸
            int buttonSize = 35;
            cardButton.setPreferredSize(new Dimension(buttonSize, buttonSize));
            cardButton.setMinimumSize(new Dimension(buttonSize, buttonSize));
            cardButton.setMaximumSize(new Dimension(buttonSize, buttonSize));

            cardButton.setFont(new Font("微软雅黑", Font.BOLD, 12));
            cardButton.setBorder(BorderFactory.createEmptyBorder());
            cardButton.setFocusPainted(false);
            cardButton.setMargin(new Insets(0, 0, 0, 0));

            updateCardButtonStyle(cardButton, i);

            cardButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    saveCurrentAnswer();
                    loadQuestion(index);
                }
            });

            // 添加悬停效果
            cardButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    if (index != currentQuestionIndex) {
                        cardButton.setBorder(BorderFactory.createLineBorder(new Color(70, 130, 180), 2));
                    }
                }

                public void mouseExited(java.awt.event.MouseEvent evt) {
                    if (index != currentQuestionIndex) {
                        updateCardButtonStyle(cardButton, index);
                    }
                }
            });

            answerCardPanel.add(cardButton);
        }
    }

    private void updateCardButtonStyle(JButton button, int questionIndex) {
        if (questionIndex == currentQuestionIndex) {
            // 当前题目：橙色边框
            button.setBackground(new Color(255, 193, 7));
            button.setForeground(Color.BLACK);
            button.setBorder(BorderFactory.createLineBorder(new Color(255, 152, 0), 3));
        } else if (answers.containsKey(questions.get(questionIndex).getId())) {
            // 已答题：绿色
            button.setBackground(new Color(40, 167, 69));
            button.setForeground(Color.WHITE);
            button.setBorder(BorderFactory.createEmptyBorder());
        } else {
            // 未答题：浅灰色
            button.setBackground(new Color(248, 249, 250));
            button.setForeground(new Color(108, 117, 125));
            button.setBorder(BorderFactory.createLineBorder(new Color(206, 212, 218), 1));
        }
    }

    private void loadQuestion(int index) {
        if (index < 0 || index >= questions.size())
            return;

        currentQuestionIndex = index;
        Question question = questions.get(index);

        // 更新题目信息
        questionInfoLabel.setText(String.format("第 %d 题 / 共 %d 题 （%s，%.1f分）",
                index + 1, questions.size(), getQuestionTypeText(question.getQuestionType()), question.getScore()));

        // 更新题目内容
        questionLabel.setText("<html><body style='width: 750px'>" + question.getQuestionText() + "</body></html>");

        // 更新答案面板
        updateAnswerPanel(question);

        // 更新导航按钮状态
        prevButton.setEnabled(index > 0);
        nextButton.setEnabled(index < questions.size() - 1);

        // 更新答题卡
        updateAnswerCard();
    }

    private void updateAnswerPanel(Question question) {
        answerPanel.removeAll();
        answerPanel.setLayout(new BorderLayout(10, 10));

        String questionType = question.getQuestionType();
        String currentAnswer = answers.getOrDefault(question.getId(), "");

        if ("single_choice".equals(questionType) || "multiple_choice".equals(questionType)) {
            JPanel choicesPanel = new JPanel();
            choicesPanel.setLayout(new BoxLayout(choicesPanel, BoxLayout.Y_AXIS));
            choicesPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            choicesPanel.setBackground(Color.WHITE);

            ButtonGroup group = null;
            if ("single_choice".equals(questionType)) {
                group = new ButtonGroup();
            }

            // 解析已保存的答案
            String[] selectedOptions = currentAnswer.isEmpty() ? new String[0] : currentAnswer.split(",");

            for (QuestionOption option : question.getOptions()) {
                JPanel optionPanel = new JPanel(new BorderLayout(15, 0));
                optionPanel.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(233, 236, 239), 1),
                        BorderFactory.createEmptyBorder(12, 15, 12, 15)));
                optionPanel.setBackground(new Color(248, 249, 250));

                AbstractButton optionButton;
                if ("single_choice".equals(questionType)) {
                    optionButton = new JRadioButton();
                    group.add(optionButton);

                    // 检查是否已选择
                    for (String selectedOption : selectedOptions) {
                        if (selectedOption.equals(option.getOptionLabel())) {
                            optionButton.setSelected(true);
                            optionPanel.setBackground(new Color(217, 237, 247));
                            break;
                        }
                    }
                } else { // multiple_choice
                    optionButton = new JCheckBox();

                    // 检查是否已选择
                    for (String selectedOption : selectedOptions) {
                        if (selectedOption.equals(option.getOptionLabel())) {
                            optionButton.setSelected(true);
                            optionPanel.setBackground(new Color(217, 237, 247));
                            break;
                        }
                    }
                }

                optionButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
                optionButton.setBackground(optionPanel.getBackground());
                optionButton.setActionCommand(option.getOptionLabel());

                JLabel optionLabel = new JLabel(option.getOptionLabel() + ". " + option.getOptionText());
                optionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));

                // 添加选择事件监听
                final JPanel finalOptionPanel = optionPanel;
                optionButton.addActionListener(e -> {
                    if (optionButton.isSelected()) {
                        finalOptionPanel.setBackground(new Color(217, 237, 247));
                        optionButton.setBackground(new Color(217, 237, 247));
                    } else {
                        finalOptionPanel.setBackground(new Color(248, 249, 250));
                        optionButton.setBackground(new Color(248, 249, 250));
                    }
                });

                optionPanel.add(optionButton, BorderLayout.WEST);
                optionPanel.add(optionLabel, BorderLayout.CENTER);

                choicesPanel.add(optionPanel);
                choicesPanel.add(Box.createVerticalStrut(8));
            }

            JScrollPane scrollPane = new JScrollPane(choicesPanel);
            scrollPane.setBorder(BorderFactory.createEmptyBorder());
            scrollPane.getVerticalScrollBar().setUnitIncrement(16);
            answerPanel.add(scrollPane, BorderLayout.CENTER);
        } else if ("true_false".equals(questionType)) {
            // 判断题界面
            JPanel trueFalsePanel = new JPanel(new BorderLayout(10, 10));
            trueFalsePanel.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
            trueFalsePanel.setBackground(Color.WHITE);

            JLabel instructionLabel = new JLabel("请选择正确答案：");
            instructionLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
            instructionLabel.setForeground(new Color(70, 130, 180));

            JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 20));
            optionsPanel.setBackground(Color.WHITE);

            JRadioButton trueButton = new JRadioButton("正确 (True)");
            JRadioButton falseButton = new JRadioButton("错误 (False)");

            trueButton.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            falseButton.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            trueButton.setBackground(Color.WHITE);
            falseButton.setBackground(Color.WHITE);
            trueButton.setActionCommand("true");
            falseButton.setActionCommand("false");

            // 设置当前答案
            if ("true".equals(currentAnswer)) {
                trueButton.setSelected(true);
            } else if ("false".equals(currentAnswer)) {
                falseButton.setSelected(true);
            }

            ButtonGroup trueFalseGroup = new ButtonGroup();
            trueFalseGroup.add(trueButton);
            trueFalseGroup.add(falseButton);

            // 美化选项按钮
            JPanel truePanel = new JPanel(new BorderLayout());
            truePanel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(40, 167, 69), 2),
                    BorderFactory.createEmptyBorder(15, 25, 15, 25)));
            truePanel.setBackground(new Color(248, 255, 248));
            truePanel.add(trueButton, BorderLayout.CENTER);

            JPanel falsePanel = new JPanel(new BorderLayout());
            falsePanel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(220, 53, 69), 2),
                    BorderFactory.createEmptyBorder(15, 25, 15, 25)));
            falsePanel.setBackground(new Color(255, 248, 248));
            falsePanel.add(falseButton, BorderLayout.CENTER);

            optionsPanel.add(truePanel);
            optionsPanel.add(falsePanel);

            trueFalsePanel.add(instructionLabel, BorderLayout.NORTH);
            trueFalsePanel.add(optionsPanel, BorderLayout.CENTER);

            answerPanel.add(trueFalsePanel, BorderLayout.CENTER);
        } else if ("fill_blank".equals(questionType)) {
            JPanel fieldPanel = new JPanel(new BorderLayout(10, 10));
            fieldPanel.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
            fieldPanel.setBackground(Color.WHITE);

            JLabel answerLabel = new JLabel("请输入答案：");
            answerLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
            answerLabel.setForeground(new Color(70, 130, 180));

            JTextField answerField = new JTextField(currentAnswer);
            answerField.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            answerField.setPreferredSize(new Dimension(900, 50));
            answerField.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                    BorderFactory.createEmptyBorder(10, 15, 10, 15)));

            fieldPanel.add(answerLabel, BorderLayout.NORTH);
            fieldPanel.add(Box.createVerticalStrut(10), BorderLayout.CENTER);
            fieldPanel.add(answerField, BorderLayout.SOUTH);

            answerPanel.add(fieldPanel, BorderLayout.NORTH);
        } else if ("essay".equals(questionType)) {
            JPanel essayPanel = new JPanel(new BorderLayout(10, 10));
            essayPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            essayPanel.setBackground(Color.WHITE);

            JLabel essayLabel = new JLabel("请输入答案：");
            essayLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
            essayLabel.setForeground(new Color(70, 130, 180));

            JTextArea answerArea = new JTextArea(currentAnswer);
            answerArea.setFont(new Font("微软雅黑", Font.PLAIN, 16));
            answerArea.setLineWrap(true);
            answerArea.setWrapStyleWord(true);
            answerArea.setRows(15);
            answerArea.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

            JScrollPane scrollPane = new JScrollPane(answerArea);
            scrollPane.setBorder(BorderFactory.createLineBorder(new Color(70, 130, 180), 2));
            scrollPane.setPreferredSize(new Dimension(1000, 350));

            essayPanel.add(essayLabel, BorderLayout.NORTH);
            essayPanel.add(scrollPane, BorderLayout.CENTER);

            answerPanel.add(essayPanel, BorderLayout.CENTER);
        }

        answerPanel.revalidate();
        answerPanel.repaint();
    }

    private void saveCurrentAnswer() {
        if (currentQuestionIndex < 0 || currentQuestionIndex >= questions.size())
            return;

        Question question = questions.get(currentQuestionIndex);
        String answer = getCurrentAnswer();

        if (answer != null && !answer.trim().isEmpty()) {
            answers.put(question.getId(), answer);
        } else {
            answers.remove(question.getId());
        }
    }

    private String getCurrentAnswer() {
        Question question = questions.get(currentQuestionIndex);
        String questionType = question.getQuestionType();

        if (question.isChoiceQuestion()) {
            StringBuilder answer = new StringBuilder();

            // 遍历答案面板中的组件
            Component[] components = answerPanel.getComponents();
            for (Component comp : components) {
                if (comp instanceof JScrollPane) {
                    JScrollPane scrollPane = (JScrollPane) comp;
                    Component view = scrollPane.getViewport().getView();
                    if (view instanceof JPanel) {
                        JPanel choicesPanel = (JPanel) view;
                        Component[] choiceComponents = choicesPanel.getComponents();

                        for (Component choiceComp : choiceComponents) {
                            if (choiceComp instanceof JPanel) {
                                JPanel optionPanel = (JPanel) choiceComp;
                                Component[] optionComponents = optionPanel.getComponents();

                                for (Component optionComp : optionComponents) {
                                    if (optionComp instanceof JRadioButton) {
                                        JRadioButton radio = (JRadioButton) optionComp;
                                        if (radio.isSelected()) {
                                            return radio.getActionCommand();
                                        }
                                    } else if (optionComp instanceof JCheckBox) {
                                        JCheckBox checkBox = (JCheckBox) optionComp;
                                        if (checkBox.isSelected()) {
                                            if (answer.length() > 0)
                                                answer.append(",");
                                            answer.append(checkBox.getActionCommand());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return answer.toString();
        } else if ("true_false".equals(questionType)) {
            // 判断题答案获取
            Component[] components = answerPanel.getComponents();
            for (Component comp : components) {
                if (comp instanceof JPanel) {
                    JPanel trueFalsePanel = (JPanel) comp;
                    Component[] panelComponents = trueFalsePanel.getComponents();

                    for (Component panelComp : panelComponents) {
                        if (panelComp instanceof JPanel) {
                            JPanel optionsPanel = (JPanel) panelComp;
                            Component[] optionComponents = optionsPanel.getComponents();

                            for (Component optionComp : optionComponents) {
                                if (optionComp instanceof JPanel) {
                                    JPanel buttonPanel = (JPanel) optionComp;
                                    Component[] buttonComponents = buttonPanel.getComponents();

                                    for (Component buttonComp : buttonComponents) {
                                        if (buttonComp instanceof JRadioButton) {
                                            JRadioButton radio = (JRadioButton) buttonComp;
                                            if (radio.isSelected()) {
                                                return radio.getActionCommand();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return null;
        } else if ("fill_blank".equals(questionType) || "essay".equals(questionType)) {
            // 填空题和问答题答案获取
            Component[] components = answerPanel.getComponents();
            for (Component comp : components) {
                if (comp instanceof JPanel) {
                    JPanel panel = (JPanel) comp;
                    Component[] panelComponents = panel.getComponents();

                    for (Component panelComp : panelComponents) {
                        if (panelComp instanceof JTextField) {
                            JTextField textField = (JTextField) panelComp;
                            return textField.getText();
                        } else if (panelComp instanceof JScrollPane) {
                            JScrollPane scrollPane = (JScrollPane) panelComp;
                            Component view = scrollPane.getViewport().getView();
                            if (view instanceof JTextArea) {
                                JTextArea textArea = (JTextArea) view;
                                return textArea.getText();
                            }
                        }
                    }
                }
            }
        }

        return null;
    }

    private void updateAnswerCard() {
        Component[] components = answerCardPanel.getComponents();
        for (int i = 0; i < components.length && i < questions.size(); i++) {
            if (components[i] instanceof JButton) {
                updateCardButtonStyle((JButton) components[i], i);
            }
        }
        answerCardPanel.repaint();

        // 同时更新统计信息
        updateStatsPanel();
    }

    private void startTimer() {
        examTimer = new Timer(1000, e -> {
            remainingTime--;
            updateTimeDisplay();

            if (remainingTime <= 0) {
                examTimer.stop();
                JOptionPane.showMessageDialog(this, "考试时间到！系统将自动提交。", "时间到", JOptionPane.WARNING_MESSAGE);
                submitExam();
            }
        });
        examTimer.start();
    }

    private void calculateRemainingTime() {
        long now = System.currentTimeMillis();
        long examEndTime = exam.getEndTime().getTime();
        long examDuration = exam.getDuration() * 60 * 1000L; // 转换为毫秒

        if (examRecord != null && examRecord.getStartTime() != null) {
            long examStartTime = examRecord.getStartTime().getTime();
            long timeUsed = now - examStartTime;
            remainingTime = Math.max(0, (examDuration - timeUsed) / 1000);
        } else {
            remainingTime = examDuration / 1000;
        }

        // 确保不超过考试结束时间
        long timeToEnd = (examEndTime - now) / 1000;
        remainingTime = Math.min(remainingTime, timeToEnd);
    }

    private void updateTimeDisplay() {
        long hours = remainingTime / 3600;
        long minutes = (remainingTime % 3600) / 60;
        long seconds = remainingTime % 60;

        String timeText = String.format("剩余时间：%02d:%02d:%02d", hours, minutes, seconds);
        timeLabel.setText(timeText);

        // 时间不足时变红色
        if (remainingTime <= 300) { // 5分钟
            timeLabel.setForeground(Color.RED);
        } else if (remainingTime <= 600) { // 10分钟
            timeLabel.setForeground(Color.ORANGE);
        }
    }

    private void submitExam() {
        saveCurrentAnswer();

        int result = JOptionPane.showConfirmDialog(
                this,
                "确定要提交考试吗？提交后不能修改答案！",
                "确认提交",
                JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            // 保存所有答案并计算分数
            double totalScore = 0.0;

            for (Question question : questions) {
                String answer = answers.get(question.getId());
                if (answer != null) {
                    double score = answerDAO.calculateAutoGradeScore(question.getId(), answer);
                    answerDAO.saveAnswer(examRecord.getId(), question.getId(), answer, score);
                    totalScore += score;
                }
            }

            // 更新考试记录
            examRecord.setSubmitTime(new java.sql.Timestamp(System.currentTimeMillis()));
            examRecord.setTotalScore(totalScore);
            examRecord.setStatus("submitted");
            examRecordDAO.updateExamRecord(examRecord);

            if (examTimer != null) {
                examTimer.stop();
            }

            JOptionPane.showMessageDialog(this,
                    "考试提交成功！\n您的得分：" + totalScore + " / " + exam.getTotalScore(),
                    "提交成功",
                    JOptionPane.INFORMATION_MESSAGE);

            dispose();
            new StudentMainFrame(student).setVisible(true);
        }
    }

    private String getQuestionTypeText(String type) {
        switch (type) {
            case "single_choice":
                return "单选题";
            case "multiple_choice":
                return "多选题";
            case "true_false":
                return "判断题";
            case "fill_blank":
                return "填空题";
            case "essay":
                return "问答题";
            default:
                return type;
        }
    }

    // 添加统计标签作为实例变量，以便动态更新
    private JLabel answeredCountLabel;
    private JLabel unansweredCountLabel;

    private JPanel createStatsPanel() {
        JPanel panel = new JPanel(new GridLayout(3, 2, 10, 8));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "答题统计",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 16),
                new Color(70, 130, 180)));
        panel.setBackground(Color.WHITE);
        panel.setPreferredSize(new Dimension(380, 120));

        Font labelFont = new Font("微软雅黑", Font.PLAIN, 14);
        Font valueFont = new Font("微软雅黑", Font.BOLD, 14);

        JLabel totalLabel = new JLabel("总题数：");
        totalLabel.setFont(labelFont);
        JLabel totalValue = new JLabel(String.valueOf(questions.size()));
        totalValue.setFont(valueFont);
        totalValue.setForeground(new Color(70, 130, 180));

        JLabel answeredLabel = new JLabel("已答题：");
        answeredLabel.setFont(labelFont);
        answeredCountLabel = new JLabel("0");
        answeredCountLabel.setFont(valueFont);
        answeredCountLabel.setForeground(new Color(40, 167, 69));

        JLabel unansweredLabel = new JLabel("未答题：");
        unansweredLabel.setFont(labelFont);
        unansweredCountLabel = new JLabel(String.valueOf(questions.size()));
        unansweredCountLabel.setFont(valueFont);
        unansweredCountLabel.setForeground(new Color(220, 53, 69));

        panel.add(totalLabel);
        panel.add(totalValue);
        panel.add(answeredLabel);
        panel.add(answeredCountLabel);
        panel.add(unansweredLabel);
        panel.add(unansweredCountLabel);

        return panel;
    }

    private void updateStatsPanel() {
        int answeredCount = answers.size();
        int unansweredCount = questions.size() - answeredCount;

        if (answeredCountLabel != null) {
            answeredCountLabel.setText(String.valueOf(answeredCount));
        }
        if (unansweredCountLabel != null) {
            unansweredCountLabel.setText(String.valueOf(unansweredCount));
        }
    }
}